package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.DeviceGroup;
import com.example.entity.DeviceImage;
import com.example.service.DeviceGroupService;
import com.example.service.DeviceImageService;
import com.example.vo.DeviceGroupVO;
import com.example.vo.DeviceImageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备分组管理控制器
 */
@RestController
@RequestMapping("/device-group")
@Slf4j
public class DeviceGroupController {

    @Resource
    private DeviceGroupService deviceGroupService;

    @Resource
    private DeviceImageService deviceImageService;

    /**
     * 获取所有设备分组（包含设备图片）
     */
    @GetMapping("/all-with-images")
    public Result<List<DeviceGroupVO>> getAllGroupsWithImages() {
        try {
            // 获取所有分组
            List<DeviceGroup> groups = deviceGroupService.list(
                new LambdaQueryWrapper<DeviceGroup>()
                    .orderByAsc(DeviceGroup::getSortOrder)
                    .orderByAsc(DeviceGroup::getId)
            );

            // 转换为VO并填充设备图片
            List<DeviceGroupVO> groupVOs = groups.stream().map(group -> {
                DeviceGroupVO vo = new DeviceGroupVO();
                BeanUtils.copyProperties(group, vo);

                // 获取该分组下的设备图片
                List<DeviceImage> images = deviceImageService.list(
                    new LambdaQueryWrapper<DeviceImage>()
                        .eq(DeviceImage::getGroupId, group.getId())
                        .orderByAsc(DeviceImage::getId)
                );

                // 转换为设备图片VO
                List<DeviceImageVO> imageVOs = images.stream().map(image -> {
                    DeviceImageVO imageVO = new DeviceImageVO();
                    BeanUtils.copyProperties(image, imageVO);
                    imageVO.setGroupName(group.getGroupName());
                    return imageVO;
                }).collect(Collectors.toList());

                vo.setDeviceImages(imageVOs);
                return vo;
            }).collect(Collectors.toList());

            return Result.success(groupVOs);
        } catch (Exception e) {
            log.error("获取设备分组失败", e);
            return Result.error("获取设备分组失败");
        }
    }

    /**
     * 获取所有设备分组
     */
    @GetMapping("/all")
    public Result<List<DeviceGroupVO>> getAllGroups() {
        try {
            List<DeviceGroup> groups = deviceGroupService.list(
                new LambdaQueryWrapper<DeviceGroup>()
                    .orderByAsc(DeviceGroup::getSortOrder)
                    .orderByAsc(DeviceGroup::getId)
            );

            List<DeviceGroupVO> groupVOs = groups.stream().map(group -> {
                DeviceGroupVO vo = new DeviceGroupVO();
                BeanUtils.copyProperties(group, vo);
                return vo;
            }).collect(Collectors.toList());

            return Result.success(groupVOs);
        } catch (Exception e) {
            log.error("获取设备分组失败", e);
            return Result.error("获取设备分组失败");
        }
    }

    /**
     * 分页查询设备分组
     */
    @GetMapping("/page")
    public Result<Page<DeviceGroupVO>> getGroupPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String groupName) {
        try {
            Page<DeviceGroup> pageParam = new Page<>(page, size);
            
            LambdaQueryWrapper<DeviceGroup> queryWrapper = new LambdaQueryWrapper<>();
            if (groupName != null && !groupName.trim().isEmpty()) {
                queryWrapper.like(DeviceGroup::getGroupName, groupName.trim());
            }
            queryWrapper.orderByAsc(DeviceGroup::getSortOrder)
                       .orderByAsc(DeviceGroup::getId);

            Page<DeviceGroup> result = deviceGroupService.page(pageParam, queryWrapper);

            // 转换为VO
            Page<DeviceGroupVO> voPage = new Page<>();
            BeanUtils.copyProperties(result, voPage);

            List<DeviceGroupVO> voList = result.getRecords().stream().map(group -> {
                DeviceGroupVO vo = new DeviceGroupVO();
                BeanUtils.copyProperties(group, vo);
                return vo;
            }).collect(Collectors.toList());

            voPage.setRecords(voList);
            return Result.success(voPage);
        } catch (Exception e) {
            log.error("分页查询设备分组失败", e);
            return Result.error("分页查询设备分组失败");
        }
    }

    /**
     * 根据ID获取设备分组详情
     */
    @GetMapping("/{id}")
    public Result<DeviceGroupVO> getGroupDetail(@PathVariable String id) {
        try {
            DeviceGroup group = deviceGroupService.getById(id);
            if (group == null) {
                return Result.error("设备分组不存在");
            }

            DeviceGroupVO vo = new DeviceGroupVO();
            BeanUtils.copyProperties(group, vo);

            // 获取该分组下的设备图片
            List<DeviceImage> images = deviceImageService.list(
                new LambdaQueryWrapper<DeviceImage>()
                    .eq(DeviceImage::getGroupId, id)
                    .orderByAsc(DeviceImage::getId)
            );

            List<DeviceImageVO> imageVOs = images.stream().map(image -> {
                DeviceImageVO imageVO = new DeviceImageVO();
                BeanUtils.copyProperties(image, imageVO);
                imageVO.setGroupName(group.getGroupName());
                return imageVO;
            }).collect(Collectors.toList());

            vo.setDeviceImages(imageVOs);
            return Result.success(vo);
        } catch (Exception e) {
            log.error("获取设备分组详情失败", e);
            return Result.error("获取设备分组详情失败");
        }
    }

    /**
     * 创建设备分组
     */
    @PostMapping
    public Result<DeviceGroupVO> createGroup(@RequestBody DeviceGroup group) {
        try {
            // 检查分组名称是否已存在
            long count = deviceGroupService.count(
                new LambdaQueryWrapper<DeviceGroup>()
                    .eq(DeviceGroup::getGroupName, group.getGroupName())
            );
            if (count > 0) {
                return Result.error("分组名称已存在");
            }

            // 设置默认排序值
            if (group.getSortOrder() == null) {
                group.setSortOrder(0);
            }

            boolean success = deviceGroupService.save(group);
            if (success) {
                DeviceGroupVO vo = new DeviceGroupVO();
                BeanUtils.copyProperties(group, vo);
                return Result.success(vo);
            } else {
                return Result.error("创建设备分组失败");
            }
        } catch (Exception e) {
            log.error("创建设备分组失败", e);
            return Result.error("创建设备分组失败");
        }
    }

    /**
     * 更新设备分组
     */
    @PutMapping
    public Result<DeviceGroupVO> updateGroup(@RequestBody DeviceGroup group) {
        try {
            // 检查分组是否存在
            DeviceGroup existingGroup = deviceGroupService.getById(group.getId());
            if (existingGroup == null) {
                return Result.error("设备分组不存在");
            }

            // 检查分组名称是否重复（排除自己）
            long count = deviceGroupService.count(
                new LambdaQueryWrapper<DeviceGroup>()
                    .eq(DeviceGroup::getGroupName, group.getGroupName())
                    .ne(DeviceGroup::getId, group.getId())
            );
            if (count > 0) {
                return Result.error("分组名称已存在");
            }

            boolean success = deviceGroupService.updateById(group);
            if (success) {
                DeviceGroupVO vo = new DeviceGroupVO();
                BeanUtils.copyProperties(group, vo);
                return Result.success(vo);
            } else {
                return Result.error("更新设备分组失败");
            }
        } catch (Exception e) {
            log.error("更新设备分组失败", e);
            return Result.error("更新设备分组失败");
        }
    }

    /**
     * 删除设备分组
     */
    @DeleteMapping("/{id}")
    public Result<Object> deleteGroup(@PathVariable String id) {
        try {
            // 检查分组是否存在
            DeviceGroup group = deviceGroupService.getById(id);
            if (group == null) {
                return Result.error("设备分组不存在");
            }

            // 获取默认分组（ID为1的分组）
            DeviceGroup defaultGroup = deviceGroupService.getById(1L);
            if (defaultGroup == null) {
                return Result.error("默认分组不存在，无法删除");
            }

            // 将该分组下的设备图片移至默认分组
            deviceImageService.lambdaUpdate()
                .eq(DeviceImage::getGroupId, id)
                .set(DeviceImage::getGroupId, 1L)
                .update();

            // 删除分组
            boolean success = deviceGroupService.removeById(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("删除设备分组失败");
            }
        } catch (Exception e) {
            log.error("删除设备分组失败", e);
            return Result.error("删除设备分组失败");
        }
    }

    /**
     * 批量删除设备分组
     */
    @DeleteMapping("/batch")
    public Result<Object> batchDeleteGroups(@RequestBody List<String> ids) {
        try {
            // 获取默认分组
            DeviceGroup defaultGroup = deviceGroupService.getById(1L);
            if (defaultGroup == null) {
                return Result.error("默认分组不存在，无法删除");
            }

            // 将分组下的设备图片移至默认分组
            for (String id : ids) {
                deviceImageService.lambdaUpdate()
                    .eq(DeviceImage::getGroupId, id)
                    .set(DeviceImage::getGroupId, 1L)
                    .update();
            }

            // 批量删除分组
            boolean success = deviceGroupService.removeByIds(ids);
            if (success) {
                return Result.success();
            } else {
                return Result.error("批量删除设备分组失败");
            }
        } catch (Exception e) {
            log.error("批量删除设备分组失败", e);
            return Result.error("批量删除设备分组失败");
        }
    }
} 